<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <a-col :span="24">
        <a-card>
          <a-form ref="formRef" :model="modelForm.data" :labelCol="{ span: 9 }">
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.heName')"
                  v-bind="validateInfos.taName"
                  name="taName"
                >
                  <a-input v-model:value="modelForm.data.taName" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.gender')"
                  v-bind="validateInfos.taSex"
                  name="taSex"
                >
                  <a-select v-model:value="modelForm.data.taSex">
                    <a-select-option
                      v-for="(item, index) in dictLists.data[dictEnum.SEX]"
                      :key="index"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.dateOfBirth')"
                  ref="taBirthDate"
                  name="taBirthDate"
                >
                  <a-date-picker
                    style="width: 100%"
                    v-model:value="modelForm.data.taBirthDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="年月日"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.major')"
                  ref="taMajor"
                  name="taMajor"
                >
                  <a-input v-model:value="modelForm.data.taMajor" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.phone')"
                  ref="taPhone"
                  name="taPhone"
                >
                  <a-input v-model:value="modelForm.data.taPhone" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.email')"
                  ref="taEmail"
                  name="taEmail"
                >
                  <a-input v-model:value="modelForm.data.taEmail" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.certificateType')"
                  v-bind="validateInfos.taDocumentType"
                  name="taDocumentType"
                >
                  <a-select v-model:value="modelForm.data.taDocumentType">
                    <a-select-option
                      v-for="(item, index) in dictLists.data[dictEnum.DOCUMENT_TYPE]"
                      :key="index"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.idNumber')"
                  v-bind="validateInfos.taCertificateNo"
                  name="taCertificateNo"
                >
                  <a-input v-model:value="modelForm.data.taCertificateNo" maxlength="20" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('ta-manage.label.school')"
                  ref="schName"
                  name="schName"
                >
                  <a-input v-model:value="modelForm.data.schName">
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('universityVisible')"
                      >
                        选择
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item
                  :label="t('ta-manage.label.responsibleForTheSubject')"
                  ref="responsibleAccount"
                  :labelCol="{ span: 3 }"
                  name="responsibleAccount"
                >
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    v-model:value="modelForm.data.responsibleAccount"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <div class="pre-title">
          {{ t("ta-manage.title.attachmentInformation") }}
        </div>
        <a-card>
          <div class="up-file">
            <span class="label">{{ t("ta-manage.title.contract") }}：</span>
            <a-upload
              name="file"
              :customRequest="handleUpload"
              @change="handleChange"
            >
              <a-button>{{ t("ta-manage.title.uploadFiles") }}</a-button>
            </a-upload>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <school
      :visible="formState.universityVisible"
      @close="closeDialog"
      @submitSchool="selectUniversity"
    />
  </page-layout>
  <footer-button :buttons="buttons"></footer-button>
</template>

<script>
import school from "./modal/index.vue";

import { save, details, upload, adjust, dictionary } from "@/api/module/ta";
import { useI18n } from "vue-i18n";

import { Form, message, modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useRouter, useRoute } from "vue-router";

import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";

import { defineComponent, reactive, toRaw, createVNode, onMounted, ref } from "vue";
import moment from "moment";
const useForm = Form.useForm;
export default defineComponent({
  components: {
    school,
  },

  setup() {
    const { t } = useI18n();
    const router = useRouter();
    const route = useRoute();
    const formRef = ref();

    const formState = reactive({
      universityVisible: false,
      sexList: [],
    });
    const labelCol = { span: 3, offset: 12 };
    const wrapperCol = { span: 14 };

    const buttons = [
      {
        name: "save",
        type: "primary",
        code: "",
        event: () => {
          handleSave();
        },
      },
      {
        name: "reset",
        code: "",
        event: () => {
          handleReset();
        },
      },
    ];
    let dictLists = reactive({
      data: {},
    });
    let modelForm = reactive({
      data: {
        taName: "",
        taSex: "",
        taDocumentType: "",
        taCertificateNo: "",
        files: [],
      }
    });
    const fileList = reactive([]);
    const formRules = reactive({
      taName: [{ required: true, message: "请输入TA姓名" }],
      taSex: [{ required: true, message: "请输入性别" }],
      taDocumentType: [{ required: true, message: "请选择证件类型" }],
      taCertificateNo: [{ required: true, message: "请输入证件号" }],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelForm.data,
      formRules
    );
    const openDialog = (type) => {
      formState[type] = true;
    };
    const handleChange = (info) => {
      const arr = info.fileList.filter((v) => v.status !== "error");
      if (arr && arr.length) {
        modelForm.data.files = arr.map((item) => {
          return {
            url: item.response ? item.response.path || "" : "",
            businessType: 'ta',
            type: 1
          };
        });
      }
    };

    const closeDialog = (type) => {
      formState[type] = false;
    };

    const selectUniversity = (value) => {
      formState["universityVisible"] = false;
      if (value) {
        modelForm.data.schId = value.id;
        modelForm.data.schName = value.schoolCnName;
      }
    };

    const handleUpload = (data) => {
      const formData = new FormData();
      formData.append("file", data.file);
      upload(formData).then((res) => {
        if (res.code === 500) {
          message.error({ content: "上传附件失败" });
          data.onError();
        } else {
          data.onSuccess(res.data);
        }
      });
    };

    // 获取详情
    const getDetails = () => {
      const id = route.query.id || "";
      if (!id) return;
      return details({ id }).then((res) => {
        if (res.success) {
          res.data.taBirthDate = moment(res.data.taBirthDate).format('YYYY-MM-DD')
          modelForm.data = reactive({
            ...modelForm.data,
            ...res.data,
          });
        }
      });
    };

    getDetails();
    const getDctionary = () => {
      return dictionary({}).then((res) => {
        if (res.success) {
          formState.sexList = res.data;
        }
      });
    };

    getDctionary();
    // 保存
    const handleSave = () => {
      formRef.value.validate().then(() => {
        const result = toRaw(modelForm.data);
        if (result.id) {
          adjust(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: "保存成功", duration: 1 })
                  .then(() => {
                    router.push({
                      path: "/university/ta-manage",
                    });
                    formRef.value.resetFields();
                  });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
              message.warning({ content: "保存失败", duration: 1 });
            });
        } else {
          save(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: "保存成功", duration: 1 })
                  .then(() => {
                    router.push({
                      path: "/university/ta-manage",
                    });
                    formRef.value.resetFields();
                  });
              } else {
                message.warning({ content: "保存失败", duration: 1 });
              }
            })
            .catch((err) => {
              message.warning({ content: "保存失败", duration: 1 });
            });
        }
      });
    };

    const handleBack = () => {
      modal.confirm({
        title: "确定返回吗？",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确定",
        cancelText: "取消",
        onOk() {
          router.push({
            path: "/university/ta-manage",
          });
        },
      });
    };

    const handleReset = () => {
      formRef.value.resetFields();
    };

    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.SEX,
        dictEnum.DOCUMENT_TYPE,
      ]);
    });
    return {
      t,
      modelForm,
      formRules,
      labelCol,
      wrapperCol,
      openDialog,
      formState,
      handleChange,
      selectUniversity,
      closeDialog,
      handleSave,
      handleBack,
      validateInfos,
      resetFields,
      handleUpload,
      fileList,
      buttons,
      dictLists,
      dictEnum,
      formRef
    };
  },
});
</script>

<style lang="less" scoped>
.page-head {
  /deep/ .ant-page-header-heading-title {
    color: #2d8cf0;
  }
}

.pre-title {
  padding: 10px 25px;
  background-color: #f5f5f5;
  color: #555;
}

.up-file {
  width: 65%;
  display: flex;
  flex-wrap: nowrap;
  .label {
    width: 65px !important;
    line-height: 30px;
  }
  span:last-child {
    margin-left: 5px;
  }
}
</style>